//
//  ST_BTAccountInfo.swift
//  btvideo
//
//  Created by mac on 2020/6/16.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import RealmSwift
import HandyJSON
import SwiftyUserDefaults
import NIMSDK
import SwiftyAttributes
import SwiftyJSON
import KeychainAccess

let TIANKeychain = Keychain(service: "com.tian.token")

enum AccountRegisterStep:Int{
    case shorter = 0
    case longer
}

//MARK: -
class ST_BTAccountInfo: Object,HandyJSON {
    
    required override init() {
        super.init()
    }
    
    @objc dynamic var accid = ""
    
    /**
     真实id
     */
    @objc dynamic var member_id = 0
    
    /// 已支付
    @objc dynamic var ticketPaid = false
    
    /// 注册流程
    @objc dynamic var registerStepValue = 0
    
    /// 注册流程枚举
    var registerStep: AccountRegisterStep {
        get { return AccountRegisterStep(rawValue: registerStepValue) ?? .shorter }
        set { registerStepValue = newValue.rawValue }
    }
    
    
    var token:String{
        return (try? TIANKeychain.getString(SC.tian_token_key)) ?? ""
    }
    
    var im_token:String{
        return (try? TIANKeychain.getString(SC.tian_im_token_key+accid)) ?? ""
    }
    
    @objc dynamic var userinfo: ST_BTUserinfo? = nil
    
//    后台 我们项目独有
    @objc dynamic var extra_data : BTAccountExtension? = nil
    
    override static func primaryKey() -> String? {
        return "accid"
    }
    
    
}

class BTAccountExtension: Object,HandyJSON {
    
    required override init() {
        super.init()
    }
    
    @objc dynamic var accid = ""
    
//    MARK:  内购相关
    @objc dynamic var super_like = 0
    
    @objc dynamic var super_hot = false
    
    @objc dynamic var expiration_time = 0
//    可以喜欢的次数
    @objc dynamic var like_times = 0
    
//    没有封面视频可滑动次数  -1表示有封面
    @objc dynamic var slide_times = 0
//    1:审核通过，2：审核中，3：审核失败，4：无视频
    @objc dynamic var video_status = 4
    
//    同城过期时间
    @objc dynamic var same_city_expire = 0
    
    override static func primaryKey() -> String? {
        return "accid"
    }
}


class ST_BTUserinfo: Object,HandyJSON {
    
    required override init() {
        super.init()
    }
    
    @objc dynamic var accid = ""
    
    /**
     真实id
     */
    @objc dynamic var member_id = 0
    
//    @objc dynamic var token = ""
//
//    @objc dynamic var im_token = ""
    
    @objc dynamic var nickname = ""
    
    ///nearby 多少人
    @objc dynamic var total_num = 0
    
    @objc dynamic var avatar = ""
    
    @objc dynamic var gender = 0
    
    var sex: ST_SEX? {
        get { return ST_SEX(rawValue: gender) }
        set { gender = newValue?.rawValue ?? 0 }
    }
    
    @objc dynamic var birth = ""
    
    @objc dynamic var age = 18
    
    @objc dynamic var constellation = ""
    
    @objc dynamic var marriage = 0
    
    @objc dynamic var sign = ""
    
    @objc dynamic var about_self = ""
    
    @objc dynamic var want_know = ""
    
    @objc dynamic var we_can_talk_about = ""

    @objc dynamic var is_vip = false
    
    @objc dynamic var video_count = 0
    
    @objc dynamic var cover_video = ""
    
    @objc dynamic var cover_video_img = ""
    
    @objc dynamic var city_name = ""
    
    @objc dynamic var distance = ""
    
    @objc dynamic var like_number = 0
    
    
    @objc dynamic var vip_expire = 0
    
    /**
     甜心币
     */
    var sweet_coin:Float{
        return remoteSweetCoin - localConsumeSweetCoin
    }
    /**
     后台甜心币
     */
    @objc dynamic var remoteSweetCoin:Float = 0
    
    /**
     本地当前消耗的甜心币 ps:还未与后台同步的 接口 spedMatchV77/subCoin/v2.json
     */
    @objc dynamic var localConsumeSweetCoin:Float = 0
    
    /**
     免费次数  后台字段 free_quick_talk_num
     */
    @objc dynamic var freeTalkCount = 0
    
    /**
     收益
     */
    @objc dynamic var income = 0.0
    
    
    /**
     收益 out
     */
    @objc dynamic var income_out = 0.0
    
    /**
     收益 更新时间，发送消息的时间早于收益更新时间【无效】
     */
    @objc dynamic var incomeUpdateDate = Date()
    
//    /**
//     密友个数
//     */
//    @objc dynamic var chum_num = 0

    /**
     是否关注 version 2.2.2
     */
    @objc dynamic var is_attention = false
    
    /**
     关注时间
     */
    @objc dynamic var create_int = 0
    
    /**
     新增 用户 认证状态
     */
    @objc dynamic var face_audit_state = 0
    
//    统计使用 【注册日期 注册时间 想要寻求】
    @objc dynamic var register_version = ""
    
    @objc dynamic var register_time = 0
    
    @objc dynamic var personal_want_name = ""
    
    override static func primaryKey() -> String? {
        return "accid"
    }
    
    
    //    单独使用
    var coverImage:UIImage?
    
    var currentVideoTime:CMTime?
    
    var aboutMeAttribute = [UserCenterIntroAtrribute]()
    
    var aboutMeEmptyDescribe = ""
    
    var userIntroHeight = 0.cgFloat
    
    
//    fileprivate let textFont = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
//
//    fileprivate let textColor = UIColor.init(hexString: "#666660")!

 
}

extension ST_BTUserinfo{
    
    func createUserCenterData()  {
        
        let p = NSMutableParagraphStyle()
        p.lineSpacing = 5
        
        var attributeArray = [UserCenterIntroAtrribute]()
        
        var height = 0.cgFloat
        
        if !want_know.isEmpty{
            
            let str = want_know.withAttributes([Attribute.textColor(UIColor.init(hexString: "#333333")!),Attribute.font(UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)),Attribute.paragraphStyle(p)])
            
            let itemHeight = 40 + str.height(withConstrainedWidth: ScreenWidth -  29 - 36)
            
            let intro = UserCenterIntroAtrribute.init(color: UIColor.init(hexString: "#EF5F67")!, title: "我想认识的人是", atrributeStr: str, itemHeight: itemHeight)
            
            attributeArray.append(intro)
            
            
            height += itemHeight
            
        }
        
        if !about_self.isEmpty{
            
            let str = about_self.withAttributes([Attribute.textColor(UIColor.init(hexString: "#333333")!),Attribute.font(UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)),Attribute.paragraphStyle(p)])
            
            let itemHeight = 40 + str.height(withConstrainedWidth: ScreenWidth -  29 - 36)
            
            let intro = UserCenterIntroAtrribute.init(color: UIColor.init(hexString: "#5189EB")!, title: "说说我自己", atrributeStr: str, itemHeight: itemHeight)
            
            attributeArray.append(intro)
            
            if height > 0{
               height += 10
            }
            
            height += itemHeight
            
        }
        
        
        
        if !we_can_talk_about.isEmpty{
            
            let str = we_can_talk_about.withAttributes([Attribute.textColor(UIColor.init(hexString: "#333333")!),Attribute.font(UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)),Attribute.paragraphStyle(p)])
            
            let itemHeight = 40 + str.height(withConstrainedWidth: ScreenWidth -  29 - 36)
            
            let intro = UserCenterIntroAtrribute.init(color: UIColor.init(hexString: "#BC50F5")!, title: "我们可以聊聊", atrributeStr: str, itemHeight: itemHeight)
            
            attributeArray.append(intro)
            
            if height > 0{
               height += 10
            }
            
            height += itemHeight
            
        }
        
        if attributeArray.count == 0{
            
            if Defaults[.currentUserID] == accid{
                aboutMeEmptyDescribe = "😆用几句话描述一下自己吧！"
            }else{
                aboutMeEmptyDescribe = "😳他/她还没有介绍自己呢~"
            }
            
            height = 50
        }
        
        self.aboutMeAttribute = attributeArray
        
        userIntroHeight = height
        
    }
    
}


struct UserCenterIntroAtrribute {
    var color:UIColor
    var title:String
    var atrributeStr:NSAttributedString
    var itemHeight:CGFloat
}



//MARK: - PayINfo


class ST_BTUserPayinfo: Object,HandyJSON {
    
    required override init() {
        super.init()
    }
    
    @objc dynamic var accid = ""
    
    @objc dynamic var recInfo = ""
    
}

//MARK: - 语音视频通话、语音房 等
enum ST_TIAN_MEDIA_SATE_ENUM{
    
    case none
    case fallInVoiceQueue(themeId:Int?,sign:String?)
    case fallInVideoQueue(themeId:Int?,sign:String?)
    case invitingP2P
    case talkingP2P
    case waitingRespP2P
    case inVoiceChatGroup
    
    
    var rawValue:Int{
        switch self {
        case .fallInVoiceQueue:
            return 1
        case .fallInVideoQueue:
            return 2
        case .invitingP2P:
            return 3
        case .talkingP2P:
            return 4
        case .waitingRespP2P:
            return 5
        case .inVoiceChatGroup:
            return 6
        default:
            return 0
        }
    }
    
    var rawStringValue:String{

        var dict = [String : Any]()

        switch self {
        case .fallInVoiceQueue(let themeId,let sign):
            dict.updateValue(1, forKey: "rawValue")
            if let id = themeId{
                dict.updateValue(id, forKey: "themeId")
            }
            if let str = sign{
                dict.updateValue(str, forKey: "sign")
            }
        case .fallInVideoQueue(let themeId,let sign):
            dict.updateValue(2, forKey: "rawValue")
            if let id = themeId{
                dict.updateValue(id, forKey: "themeId")
            }
            if let str = sign{
                dict.updateValue(str, forKey: "sign")
            }
        case .invitingP2P:
            dict.updateValue(3, forKey: "rawValue")
        case .talkingP2P:
            dict.updateValue(4, forKey: "rawValue")
        case .waitingRespP2P:
            dict.updateValue(5, forKey: "rawValue")
        default:
            dict.updateValue(0, forKey: "rawValue")
        }

        return JSON(dictionary: dict)?.rawString() ?? ""
    }
//
    static func create(localstorage:String)->ST_TIAN_MEDIA_SATE_ENUM{

        let dict = JSON(parseJSON: localstorage)

        switch dict["rawValue"].stringValue{
        case "1":
            return .fallInVoiceQueue(themeId: dict["themeId"].int, sign: dict["sign"].string)
        case "2":
            return .fallInVideoQueue(themeId: dict["themeId"].int, sign: dict["sign"].string)
        case "3":
            return .invitingP2P
        case "4":
            return .talkingP2P
        case "5":
            return .waitingRespP2P
        default:
            return .none
        }

    }
    
}
//MARK: - 好友
class ST_BTSweetheart : Object{

    @objc dynamic var accid = ""
    @objc dynamic var avatar = ""
    @objc dynamic var nickname = ""
    @objc dynamic var vdAddress = ""
    @objc dynamic var state = 0
    @objc dynamic var hbTime = 0
    @objc dynamic var createTime:Double = 0
    @objc dynamic var birth = 0
    @objc dynamic var age = 18
    @objc dynamic var onlineTip = ""
    @objc dynamic var adress = ""
//    更新时间
    @objc dynamic var updateDate:Double = 0
    /**
     * Instantiate the instance using the passed json values to set the properties values
     */
    convenience init(fromJson json: JSON!){
        self.init()
        if json.isEmpty{
            return
        }
        accid = json["accid"].stringValue
        avatar = json["avatar"].stringValue
        nickname = json["nickname"].stringValue
        vdAddress = json["vd_address"].stringValue
        state = json["state"].intValue
        hbTime = json["hb_time"].intValue
        createTime = json["create_time"].doubleValue
        birth = json["birth"].intValue
        age = json["age"].intValue
        onlineTip = json["online_tip"].stringValue
        adress = json["adress"].stringValue
    }
    
}



